package com.ys.考试;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;

/**
 * 描述: TODO
 *
 * @author CodeYang
 * @version 2021/1/5 18:51
 */
public class P3多线程下载网络图片 {


    public static void main(String[] args) {
        String[] imageArr = {
                "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png",
                "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2568880985,498693560&fm=26&gp=0.jpg",
                "https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=3279854203,3448694990&fm=26&gp=0.jpg",
                "https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=19860963,3341724388&fm=26&gp=0.jpg",
                "https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=1127508905,2240631993&fm=26&gp=0.jpg"};


        for (String images : imageArr) {

            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        downImage(images);
                    } catch (MalformedURLException e) {
                        e.printStackTrace();
                    }
                }
            }).start();
        }


    }


        public static void downImage(String URL_PATH) throws MalformedURLException {
        URL url = new URL(URL_PATH);
        try (InputStream in = url.openStream();
             ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ) {
            byte[] data = new byte[1024];
            int len = 0;
            while ((len = in.read(data)) != -1) {
                bos.write(data, 0, len);
            }

            // 内存中字节数组中的图片的字节
            byte[] bytes = bos.toByteArray();

            String subfix = URL_PATH.substring(URL_PATH.lastIndexOf("."));
            try (
                    FileOutputStream fos = new FileOutputStream("day_25/" + System.currentTimeMillis() + subfix);
                    BufferedOutputStream buffferdos = new BufferedOutputStream(fos);
            ) {
                buffferdos.write(bytes);
            }

        } catch (Exception e) {
            System.err.println("下载异常！");
            e.printStackTrace();
        }
    }
}
